package com.kong.meirimall.ware.service.impl;

import com.kong.common.constant.WareConstant;
import com.kong.meirimall.ware.entity.PurchaseDetailEntity;
import com.kong.meirimall.ware.service.PurchaseDetailService;
import com.kong.meirimall.ware.vo.MergeVo;
import com.kong.meirimall.ware.vo.PurchaseDoneVo;
import com.kong.meirimall.ware.vo.PurchaseItemDoneVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kong.common.utils.PageUtils;
import com.kong.common.utils.Query;

import com.kong.meirimall.ware.dao.PurchaseDao;
import com.kong.meirimall.ware.entity.PurchaseEntity;
import com.kong.meirimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;
    @Autowired
    private WareSkuServiceImpl wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //若没有采购单，新建一个，并附上默认值
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            //获取新建采购单的 id
            purchaseId = purchaseEntity.getId();
        }
        // TODO 确认采购单状态是 0/1 才可以合并
        // mergeVo 接收到的是 多个采购需求id的数组 和 采购单的id
        // 根据采购需求 id 得到 采购需求实体类，更新它们的 一些属性（如状态）
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = items.stream().map(i -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        detailService.updateBatchById(detailEntities);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void receive(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item-> item.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(item->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2、改变采购单的状态
        this.updateBatchById(purchaseEntities);
        //3、改变采购项(需求 detail)的状态
        purchaseEntities.forEach(item->{
            //获得每个采购单的所有采购项
            List<PurchaseDetailEntity> detailEntities=detailService.listDetailByPurchaseId(item.getId());
            for (PurchaseDetailEntity detailEntity : detailEntities) {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.RECEIVE.getCode());
            }
            detailService.updateBatchById(detailEntities);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        //1、改变采购单状态
        //2、改变采购项的状态
        //3、将成功采购的进行入库
        Long id = doneVo.getId();
        PurchaseEntity purchaseEntity = this.getById(id);
        Boolean flag=true; //如果有一个未采购成功，就变为 false
        for (PurchaseItemDoneVo item : doneVo.getItems()) {
            PurchaseDetailEntity detailEntity = detailService.getById(item.getItemId());
            if(item.getStatus()==WareConstant.PurchaseStatusEnum.HASEERROR.getCode()){
                flag=false;
            }else {
                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            detailEntity.setStatus(item.getStatus());
            detailService.updateById(detailEntity);
        }
        purchaseEntity.setStatus(flag?WareConstant.PurchaseDetailStatusEnum.FINISH.getCode() : WareConstant.PurchaseDetailStatusEnum.HASEERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}